//
//  XMLNodeViewController.m
//  iTrack
//
//  Created by Sergei Sevriugin on 6/16/10.
//  Copyright 2010 Bellwood Systems. All rights reserved.
//

#import "XMLNodeViewController.h"

@implementation XMLNodeViewController
@synthesize root_node;
@synthesize featureProperties;
@synthesize editable;
@synthesize updated;
@synthesize child_indexPath;
@synthesize root_controller;
@synthesize sync_property_name;

#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

	NSString*			node_Name			= nil;
	NSString*			sync_Name			= nil;
	NSComparisonResult	result				= -1;
	
	node_Name								= [root_node name];
	
	[self setSync_property_name:nil];

	
	result									= [node_Name compare:@"name"];
	if (result == 0) {
		sync_Name							= [NSString stringWithString:@"title"];
		
		[self setSync_property_name:sync_Name];
		
		[self setEditable:YES];
	}
	
	result									= [node_Name compare:@"description"];
	if (result == 0) {
		sync_Name							= [NSString stringWithString:@"summary"];

		[self setSync_property_name:sync_Name];

		[self setEditable:YES];
	}
	
	self.child_indexPath					= nil;
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	if (self.updated || [root_controller saveCurrentFeature]) {
		[[self tableView] reloadData];
	}
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    if (featureProperties) {
		return 2;
	}
	else {
		return 1;
	}
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	if (section == 1 && featureProperties) {
		return [featureProperties count];
	}
	else {
		return [root_node childCount];
	}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	
	if (!featureProperties) {
		return nil;
	}
	
	NSString* SectionTitle;
	if (section == 0) {
		SectionTitle = [[[NSString alloc] initWithString:@"NODES"] autorelease]; 
	}
	else {
		SectionTitle = [[[NSString alloc] initWithString:@"PROPERTIES"] autorelease];
	}
	return SectionTitle;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	if (indexPath.section == 1 && featureProperties) {
		[[cell textLabel] setText:[(iTrackPropety*) [featureProperties objectAtIndex:indexPath.row] title]];
		[[cell detailTextLabel] setText:[(iTrackPropety*) [featureProperties objectAtIndex:indexPath.row] subtitle]];
		
		return cell;	
	}
	
    // Configure the cell...
    
	NSMutableString*	node_summary	= [[NSMutableString alloc] initWithCapacity: 1024];
	GDataXMLNode*		node			= [root_node childAtIndex:indexPath.row];
	NSUInteger			node_childCount	= [node childCount];
	GDataXMLNode*		node_child;

	
	[node_summary appendFormat:@"%@:",[node name]];
		
	for (int i = 0; i < node_childCount; i++) {
		if (i > 0) {
			[node_summary appendFormat:@"%@",@","];
		}
		node_child = [node childAtIndex:i];
		[node_summary appendFormat:@" %@",[node_child name]];
	}
	
    [[cell textLabel] setText:[node stringValue]];
	[[cell detailTextLabel] setText:node_summary];
	
	[node_summary release];
	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.

	if (indexPath.section == 1 && featureProperties) {
		
		if ([[featureProperties objectAtIndex:indexPath.row] kind] == iTrackPropetyKingText) {
			
			
			UIViewController *detailViewController = [[UIViewController alloc] initWithNibName:@"XMLTextView" bundle:nil];
			UITextView* textView = (UITextView*) [detailViewController view];
			
			[textView setText:[(iTrackPropety*) [featureProperties objectAtIndex:indexPath.row] subtitle]];
			[textView setEditable:[(iTrackPropety*) [featureProperties objectAtIndex:indexPath.row] editable]];
			
			self.child_indexPath = indexPath;
		
			[textView setDelegate:self];
			
			[self.navigationController pushViewController:detailViewController animated:YES];
			[detailViewController release];
			
			return;
		}
	}
	
	
	GDataXMLNode*		node_child = [root_node childAtIndex:indexPath.row];

	
	if ([node_child childCount] > 0 ) {
		XMLNodeViewController *detailViewController = [[XMLNodeViewController alloc] initWithNibName:@"XMLNodeView" bundle:nil];
		
		[detailViewController setRoot_node:node_child];
		[detailViewController setFeatureProperties:nil];
		[detailViewController setEditable:[self editable]];
		[detailViewController setUpdated:NO];
		[detailViewController setRoot_controller:[self root_controller]];
		
		// Pass the selected object to the new view controller.
		[self.navigationController pushViewController:detailViewController animated:YES];
		[detailViewController release];
	}
	else {
		UIViewController *detailViewController = [[UIViewController alloc] initWithNibName:@"XMLTextView" bundle:nil];
		UITextView* textView = (UITextView*) [detailViewController view];
		[textView setText:[node_child stringValue]];
		[textView setEditable:[self editable]];
		
		self.child_indexPath = indexPath;
		
		[textView setDelegate:self];
		
		[self.navigationController pushViewController:detailViewController animated:YES];
		[detailViewController release];
	}

}

#pragma mark -
#pragma mark update the feature

- (IBAction)addClicked:(id)sender {
}


#pragma mark -
#pragma mark text editing protocol

- (void)textViewDidEndEditing:(UITextView *)textView {
	
	if (self.child_indexPath.section == 1 && featureProperties) {
		iTrackPropety*	property	= [featureProperties objectAtIndex:self.child_indexPath.row];
		
		[property setSubtitle:[textView text]];
		
		[[self tableView] reloadData];
		
		self.updated = YES;

		if (root_controller) {
			[root_controller setSaveCurrentFeature:YES];
		}
	}
	
	if(self.child_indexPath.section == 0 && self.child_indexPath.row < [root_node childCount]) {
	
		GDataXMLNode*		node_child	= [root_node childAtIndex:self.child_indexPath.row];
	
		[node_child setStringValue:[textView text]];
		
		if (sync_property_name) {
			
			iTrackPropety* property		= [root_controller getFeaturePropertyByName:sync_property_name];
		
			if (property) {
				[property setSubtitle:[textView text]];
			}
		}
		
		[[self tableView] reloadData];
		
		self.updated = YES;

		if (root_controller) {
			[root_controller setSaveCurrentFeature:YES];
		}
		
	}
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

